package com.inspur.dgov.vlbod.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.inspur.dgov.vlbod.constant.UpAndCollectConstant;
import com.inspur.dgov.vlbod.entity.LiveThumbsUp;
import com.inspur.dgov.vlbod.http.DgovResponse;
import com.inspur.dgov.vlbod.secure.token.UserRecord;
import com.inspur.dgov.vlbod.service.LiveThumbsUpService;
import com.inspur.dgov.vlbod.service.UserRecordService;
import com.inspur.dgov.vlbod.util.RateLimiterUtils;
import com.inspur.dgov.vlbod.util.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 *  直播点赞服务控制器
 * </p>
 *
 * @author chiyupei
 * @since 2023-05-29
 */
@Slf4j
@RestController
@RequestMapping("/liveThumbs")
public class LiveThumbsUpController {

    /**
     * Redis直播点赞KEY
     */
    public static final String LIVE_THUMBS_UP_KEY = "liveThumbsUpZset@";

    @Autowired
    private UserRecordService userRecordService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LiveThumbsUpService liveThumbsUpService;

    @Autowired
    private RateLimiterUtils rateLimiterUtils;

    /**
     * 直播点赞
     *
     * @param id 直播ID
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/add/{id}")
    public DgovResponse add(HttpServletRequest request, @PathVariable String id) {
            try {
                //获取当前时间
                long now = System.currentTimeMillis();
                LocalDateTime localDateTimeFromTimeStamp = TimeUtils.getLocalDateTimeFromTimeStamp(now);
                // 获取当前登录用户ID
                UserRecord userRecord = this.userRecordService.getUserRecord(request);
                String userId = userRecord.getUserId();
                //限流测试
                /*if(!rateLimiterUtils.tryAcquire(UpAndCollectConstant.LIVE_LIMIT_REDIS_PREFIX,
                        userId,id,UpAndCollectConstant.DEMANDLIVE_LIMIT_MAXCOUNT,
                        UpAndCollectConstant.DEMANDLIVE_LIMIT_PERIOD)){
                    return DgovResponse.success("频繁点赞");
                }*/

                //数据库插入
                LiveThumbsUp liveThumbsUp = new LiveThumbsUp();
                liveThumbsUp.setUserId(userRecord.getUserId());
                liveThumbsUp.setBroadcastId(id);
                liveThumbsUp.setCreateTime(localDateTimeFromTimeStamp);
                //先去数据库查一下是否存在数据
                Integer count = liveThumbsUpService.lambdaQuery().
                        eq(LiveThumbsUp::getUserId, userId).eq(LiveThumbsUp::getBroadcastId, id).count();
                    //不存在就插入
                if (null==count||count<=1)
                {
                    liveThumbsUpService.save(liveThumbsUp);
                }
                else
                //存在
                {log.error("Liveup database count:{}",count);}
                //redis插入
                String redisLiveId = LIVE_THUMBS_UP_KEY + id;
                Double score = this.redisTemplate.opsForZSet().score(redisLiveId, userId);
                if (null == score || 0 == score) {
                    redisTemplate.opsForZSet().add(redisLiveId, userId, now);

                    return DgovResponse.success(now);
                }
                return DgovResponse.success(score);
            }catch(Exception e){
                log.error("Add Live up Fail:{}",e);
                return DgovResponse.fail("fail");
            }
    }
    /**
     * 取消直播点赞
     *
     * @param id 直播ID
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/delete/{id}")
    public DgovResponse delete(HttpServletRequest request, @PathVariable String id) {
        try {
            // 获取当前登录用户ID
            UserRecord userRecord = this.userRecordService.getUserRecord(request);
            String userId = userRecord.getUserId();
            //先去数据库删除
            LambdaQueryWrapper<LiveThumbsUp> liveThumbsUpWraaper = new LambdaQueryWrapper<>();
            liveThumbsUpWraaper.eq(LiveThumbsUp::getUserId, userId).eq(LiveThumbsUp::getBroadcastId, id);
            boolean remove = liveThumbsUpService.remove(liveThumbsUpWraaper);
            if (remove) {
                log.error("数据库数据删除失败:userid:{},liveId{}", userId, id);
            };
            String redisLiveId = LIVE_THUMBS_UP_KEY + id;
            Double score = this.redisTemplate.opsForZSet().score(redisLiveId, userId);
            if (null != score) {
                this.redisTemplate.opsForZSet().remove(redisLiveId, userId);
            }
            return DgovResponse.success();
        }catch (Exception e){
            log.error("remove up fail:{}",e);
            return DgovResponse.fail("remove up Fail");
        }
    }

    /**
     * 统计直播点赞数
     *
     * @param id 直播ID
     * @return
     */
    @GetMapping("/count/{id}")
    public DgovResponse count(HttpServletRequest request, @PathVariable String id) {
        String redisLiveId = LIVE_THUMBS_UP_KEY + id;
        Long count = this.redisTemplate.opsForZSet().size(redisLiveId);
        if (null == count) {
            count = 0L;
        }
        return DgovResponse.success(count);
    }

    /**
     * 检查当前用户是否已点赞
     *
     * @param id 直播ID
     * @return
     */
    @GetMapping("/check/{id}")
    public DgovResponse check(HttpServletRequest request, @PathVariable String id) {
        String redisLiveId = LIVE_THUMBS_UP_KEY + id;
        // 获取当前登录用户ID
        UserRecord userRecord = this.userRecordService.getUserRecord(request);
        String userId = userRecord.getUserId();
        Double score = this.redisTemplate.opsForZSet().score(redisLiveId, userId);
        return DgovResponse.success(null != score);
    }
}
